package com.xgzit.xgzmall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgzit.common.dto.mq.OrderDto;
import com.xgzit.common.dto.mq.SeckillOrderDto;
import com.xgzit.common.exception.NoStockException;
import com.xgzit.common.utils.PageUtils;
import com.xgzit.common.utils.Query;
import com.xgzit.common.utils.R;
import com.xgzit.common.vo.MemberEntityVo;
import com.xgzit.xgzmall.order.constant.OrderConstant;
import com.xgzit.xgzmall.order.dao.OrderDao;
import com.xgzit.xgzmall.order.dto.OrderCreateDto;
import com.xgzit.xgzmall.order.entity.OrderEntity;
import com.xgzit.xgzmall.order.entity.OrderItemEntity;
import com.xgzit.xgzmall.order.entity.PaymentInfoEntity;
import com.xgzit.xgzmall.order.enume.OrderStatusEnum;
import com.xgzit.xgzmall.order.feign.CartFeignService;
import com.xgzit.xgzmall.order.feign.MemberFeignService;
import com.xgzit.xgzmall.order.feign.ProductFeignService;
import com.xgzit.xgzmall.order.feign.WareFeignService;
import com.xgzit.xgzmall.order.interceptor.LoginUserInterceptor;
import com.xgzit.xgzmall.order.service.OrderItemService;
import com.xgzit.xgzmall.order.service.OrderService;
import com.xgzit.xgzmall.order.service.PaymentInfoService;
import com.xgzit.xgzmall.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.xgzit.xgzmall.order.constant.OrderConstant.USER_ORDER_TOKEN_PREFIX;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    MemberFeignService MemberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        // 因为有登录拦截器，能来到这里一定是已经登录的了，直接从拦截器里面的localThread拿数据就好了。
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        // 异步调用，就会丢失上下文【RequestContextHolder本质利用 Threadlocal,而Threadlocal 必须要是同一个线程】
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressTask = CompletableFuture.runAsync(() -> {
            // 子线程重新设置一下数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = MemberFeignService.getAddress(memberEntityVo.getId());
            confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> getCartItemsTask = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 远程查询购物车的数据，购物车保存在redis
            List<OrderItemVo> items = cartFeignService.getCurrentUserItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());
            R r = wareFeignService.getSkuHasStock(collect);
            List<SkuStockVo> data = r.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (Objects.nonNull(data)) {
                Map<Long, Boolean> hasStockMap = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(hasStockMap);
            }
        }, executor);

        // 优惠卷信息  用户积分
        Integer integration = memberEntityVo.getIntegration();
        confirmVo.setIntegration(integration);
        // 其他数据自动计算
        CompletableFuture.allOf(getAddressTask, getCartItemsTask).get();
        // todo 防重令牌  接口幂等性
        String token = UUID.randomUUID().toString().replace("-", "");
        // 给页面一个
        confirmVo.setOrderToken(token);
        // redis 存一个, 设置 30分钟过期
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberEntityVo.getId(), token, 30, TimeUnit.MINUTES);
        return confirmVo;
    }

    /**
     * 本地事务，在分布式系统只能控制自己的回滚，无法控制其他服务的回滚
     * 事务使用代理对象来控制，同一个对象里面的 事务方法互相调用  内部事务设置是不生效的，原因是绕过了代理对象
     * 解决：使用代理对象来调用事务方法
     * 1、引入 Aop-Starter spring-boot-starter-aop  利用里面的 aspectj
     * 2、开启 @EnableAspectJAutoProxy(exposeProxy = true)  并暴露代理对象设置为true
     * 这样动态代理都是 aspectj 代理【即使没有接口，也可以创建动态代理】
     * 3、本类方法就 使用代理对象去调用  AopContext.currentProxy() 拿到当前代理对象
     * 分布式事务：产生的原因主要是 网络问题，以及分布式机器
     * mysql 默认是 可重复读  oracle 默认是读已提交
     * 传播行为 required、required_new
     * <p>
     * c:Consistency一致性【数据同时是否一致】
     * A：availability可用性  【一部分故障，整体是否还能响应请求】
     * P:Partition tolerance 分区容错性 【多个子网络，一个子网络一个区，区间网络通信可能失败】 必须要！
     * CP 、AP
     * 一致性算法： raft、paxos等
     * 强一致、弱一致【忍受某些功能不可用、同步中的状态】、最终一致性
     **/
    @Transactional(timeout = 30)
    public void a() {
        OrderServiceImpl proxy = (OrderServiceImpl) AopContext.currentProxy();
        proxy.b();
        proxy.c();
    }

    @Transactional(propagation = Propagation.REQUIRED, timeout = 4)
    public void b() {

    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 20)
    public void c() {

    }

    //    @GlobalTransactional
    @Transactional(isolation = Isolation.READ_COMMITTED)
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        // todo 原子操作
        SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
        // 利用ThreadLocal 同线程共享数据
        confirmVoThreadLocal.set(vo);
        responseVo.setCode(0);
        // 去创建订单，验令牌，验价格，锁库存
        // 1、验证令牌[令牌的对比和删除必须保证原子性]
        // 0 代表令牌校验失败  1：删除成功！
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        String orderToken = vo.getOrderToken();
        // 拦截器获取当前用户
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        // 使用脚本 原子验证和删除令牌
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(USER_ORDER_TOKEN_PREFIX + memberEntityVo.getId()), orderToken);
        if (result == 0L) {
            // 令牌验证失败
            responseVo.setCode(1);
            return responseVo;
        } else {
            // 令牌验证成功
            // 1、创建订单、订单项等信息
            OrderCreateDto order = createOrder();
            // 2、验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                // 金额对比成功
                // TODO 3、保存订单
                saveOrder(order);
                // 4、库存锁定 【锁库存失败还要撤销订单】
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVos = order.getItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(orderItemVos);
                // todo 4、远程锁库存
                // 为了保证高并发，库存服务自己回滚  可以发消息给库存服务
                // 库存服务本身也可以使用自动解锁模式   消息队列
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    responseVo.setOrder(order.getOrder());
                    // todo 5、远程扣减积分
                    // int a = 10/0; // 订单回滚、库存不回滚
                    // todo 订单创建成功发送消息给 mq
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
                    return responseVo;
                } else {
                    // 锁定失败 code 3 表示库存不足失败
                    throw new NoStockException();
                   /* responseVo.setCode(3);
                    return responseVo;*/
                }
            } else {
                responseVo.setCode(2);
                return responseVo;
            }
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getOrderSn, orderSn));
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        // 收到的消息是每一个创建成功的订单，关闭订单之前需要先查询订单状态
        OrderEntity orderEntity = this.getById(entity.getId());
        // 订单只有在 待付款才能关闭订单
        if (OrderStatusEnum.CREATE_NEW.getCode().equals(orderEntity.getStatus())) {
            // 关闭订单就是修改订单状态  不要用消息队列里面的实体，因为过了30分钟，属性有可能已发生变化
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(orderEntity, orderDto);
            try {
                // todo 保证消息一定要发送出去，每一个发送的消息都可以做好日子记录[数据库保存每一个消息的详细信息]
                // 定期扫描数据库 将失败的消息再发送一遍
                // 解锁订单成功 发送消息给 解锁库存 防止因为网络、卡顿等原因造成 订单解锁而库存不解锁
                // 以 路由键 order.release.other 发送 orderDto 这个消息给 order-event-exchange 交换机
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderDto);
            } catch (Exception e) {
                // todo 出现问题  将没有发送成功的消息进行重试发送

            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity orderByOrderSn = this.getOrderByOrderSn(orderSn);
        // 查出订单项的数据
        List<OrderItemEntity> list = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>()
                .eq(OrderItemEntity::getOrderSn, orderSn));
        OrderItemEntity itemEntity = list.get(0);
        String skuName = itemEntity.getSkuName();
        // 金额需要处理成保留2位 如果第三位开始不是0 就向上取值
        payVo.setTotal_amount(orderByOrderSn.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString());
        payVo.setOut_trade_no(orderSn);
        // 就拿订单项的第一个商品的标题作为订单名称
        payVo.setSubject(skuName);
        // 拿 第一个商品的销售属性作为 备注
        payVo.setBody(itemEntity.getSkuAttrsVals());
        return payVo;
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        // 拦截器就有当前用户的 信息
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new LambdaQueryWrapper<OrderEntity>()
                        .eq(OrderEntity::getMemberId,memberEntityVo.getId())
                        .orderByDesc(OrderEntity::getId)
        );
        List<OrderEntity> collect = page.getRecords().stream().map(order -> {
            // 安装订单号 查询订单项信息
            List<OrderItemEntity> list = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>()
                    .eq(OrderItemEntity::getOrderSn, order.getOrderSn()));
            order.setItemEntityList(list);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(collect);
        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo vo) {
        // 1、保存交易流水
        PaymentInfoEntity infoEntity = new PaymentInfoEntity();
        // 交易流水
        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        // 订单号
        infoEntity.setOrderSn(vo.getOut_trade_no());
        // 订单状态
        infoEntity.setPaymentStatus(vo.getTrade_status());
        // 创建时间
        infoEntity.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(infoEntity);
        // 2、修改订单状态信息
        if(vo.getTrade_status().equals("TRADE_SUCCESS") || vo.getTrade_status().equals("TRADE_FINISHED")){
            this.updateOrderStatus(vo.getOut_trade_no(), OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void updateOrderStatus(String orderSn, Integer code) {
        this.baseMapper.updateOrderStatus(orderSn, code);
    }

    @Override
    public void createSeckillOrder(SeckillOrderDto orderDto) {
        // todo 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderDto.getOrderSn());
        orderEntity.setMemberId(orderEntity.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = orderDto.getSeckillPrice().multiply(new BigDecimal(String.valueOf(orderDto.getNum())));
        orderEntity.setPayAmount(multiply);
        save(orderEntity);
        // todo 保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(orderDto.getOrderSn());
        itemEntity.setRealAmount(multiply);
        itemEntity.setSkuQuantity(orderDto.getNum());
        itemEntity.setSkuId(orderDto.getSkuId());
        R r = productFeignService.getSpuInfoBySkuId(orderDto.getSkuId());
        if (r.getCode()==0){
            SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
            });
            // todo 设置其他信息
            itemEntity.setSpuName(data.getSpuName());
            itemEntity.setCategoryId(data.getCatalogId());
        }
        orderItemService.save(itemEntity);
    }

    /**
     * 保存订单数据
     **/
    private void saveOrder(OrderCreateDto order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> items = order.getItems();
        orderItemService.saveBatch(items);
    }

    /**
     * 创建订单
     *
     * @return com.xgzit.xgzmall.order.dto.OrderCreateDto
     */
    private OrderCreateDto createOrder() {
        OrderCreateDto createDto = new OrderCreateDto();
        // 生成订单号
        String orderSn = IdWorker.getTimeId();
        // 1、构建订单
        OrderEntity entity = buildOrder(orderSn);
        createDto.setOrder(entity);
        // 2、订单项信息
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);
        createDto.setItems(itemEntities);
        // 3、计算价格
        computerPrice(entity, itemEntities);
        return createDto;
    }

    private void computerPrice(OrderEntity entity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal giftGrowth = new BigDecimal("0.0");
        BigDecimal giftIntegration = new BigDecimal("0.0");
        // 订单的总额，叠加每个订单项的金额
        for (OrderItemEntity itemEntity : itemEntities) {
            coupon = coupon.add(itemEntity.getCouponAmount());
            integration = integration.add(itemEntity.getIntegrationAmount());
            promotion = promotion.add(itemEntity.getPromotionAmount());
            total = total.add(itemEntity.getRealAmount());
            giftIntegration = giftIntegration.add(new BigDecimal(itemEntity.getGiftIntegration().toString()));
            giftGrowth = giftGrowth.add(new BigDecimal(itemEntity.getGiftGrowth().toString()));

        }
        // 1、订单价格相关
        entity.setTotalAmount(total);
        // 应付总额
        entity.setPayAmount(total.add(entity.getFreightAmount()));
        entity.setPromotionAmount(promotion);
        entity.setIntegrationAmount(integration);
        entity.setPromotionAmount(promotion);
        // 设置积分和成长值
        entity.setIntegration(giftIntegration.intValue());
        entity.setGrowth(giftGrowth.intValue());
        entity.setDeleteStatus(0);
    }

    private OrderEntity buildOrder(String orderSn) {
        MemberEntityVo memberEntityVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(memberEntityVo.getId());
        // 1、获取收货地址信息
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        R fare = wareFeignService.getFare(submitVo.getAddrId());
        if (fare.getCode() == 0) {
            FareVo fareVo = fare.getData(new TypeReference<FareVo>() {
            });
            // 设置运费
            entity.setFreightAmount(fareVo.getFare());
            // 设置收货人信息
            entity.setReceiverCity(fareVo.getAddress().getCity());
            entity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
            entity.setReceiverName(fareVo.getAddress().getName());
            entity.setReceiverPhone(fareVo.getAddress().getPhone());
            entity.setReceiverPostCode(fareVo.getAddress().getPostCode());
            entity.setReceiverProvince(fareVo.getAddress().getProvince());
            entity.setReceiverRegion(fareVo.getAddress().getRegion());
        }
        // 设置订单状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }

    /**
     * 构建订单项列表
     *
     * @return java.util.List<com.xgzit.xgzmall.order.entity.OrderItemEntity>
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 最后确定每个购物项的价格
        List<OrderItemVo> userItems = cartFeignService.getCurrentUserItems();
        if (Objects.nonNull(userItems) && !CollectionUtils.isEmpty(userItems)) {
            List<OrderItemEntity> itemEntities = userItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /**
     * 订单项的构建
     *
     * @param cartItem:
     * @return com.xgzit.xgzmall.order.entity.OrderItemEntity
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        //  1、订单信息 订单号
        // 2、商品的SPU
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        if (r.getCode() == 0) {
            SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
            });
            itemEntity.setSpuId(data.getId());
            itemEntity.setSpuBrand(data.getBrandId().toString());
            itemEntity.setSpuName(data.getSpuName());
            itemEntity.setCategoryId(data.getCatalogId());
        }
        // 3、商品的sku
        itemEntity.setSkuId(skuId);
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        // string工具类  传入指定的分隔符 变成字符串
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        // 4、商品的优惠信息 忽略，不做
        // 5、商品赠送的积分、成长值
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        // 5、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        // 当前订单项的实际金额 = 总额 - 优惠
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal real = orign.subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getIntegrationAmount());

        itemEntity.setRealAmount(real);
        return itemEntity;
    }
}
